<?php
/**
 * @package		简易CMS
 * @subpackage	缓存：插件
 * @version		$Id: function_member.php 19 2012-06-07 17:36:32Z htmambo@gmail.com $
 * @author		Hoping
 * @copyright	Copyright (C) 2010 Hoping Software Studio.
 */

if (!defined('IN_JYCMS')) {
	exit('Access Denied');
}

/**
 * 检查列表页面是否已经超出了系统允许的范围
 * @global array $_G 系统全局变量
 * @param int $start 起始记录数
 * @param int $perpage 每页显示记录数
 */
function ckstart($start, $perpage) {
	global $_G;
	$_G['setting']['maxpage'] = $_G['setting']['maxpage'] ? $_G['setting']['maxpage'] : 100;
	$maxstart = $perpage * intval($_G['setting']['maxpage']);
	if ($start < 0 || ($maxstart > 0 && $start >= $maxstart)) {
		showmessage('length_is_not_within_the_scope_of');
	}
}

/**
 * 用户登录
 * @param anytype $username 登录用的用户ID/注册邮箱/用户名
 * @param <type> $password 密码
 * @param <type> $questionid 提示问题ID
 * @param <type> $answer 答案
 * @param <type> $loginfield 登录检测字段名
 * @return array 登录成功后的用户信息
 */
function userlogin($username, $password, $questionid, $answer, $loginfield = 'username') {
	$return = array();

	if ($loginfield == 'uid') {
		$isuid = 1;
	} elseif ($loginfield == 'email') {
		$isuid = 2;
	} elseif ($loginfield == 'auto') {
		$isuid = 3;
	} else {
		$isuid = 0;
	}
	$sql = "SELECT * FROM #__common_member WHERE ";
	$password = md5($password);
	$where['pass'] = "password='$password'";
	if ($questionid > 0) {
		$where['sec'] = "secques='" . quescrypt($questionid, $answer) . "'";
	} else {
		$where['sec'] = "secques=''";
	}
	if ($isuid == 3) {
		if (preg_match('/^[1-9]\d*$/', $username)) {
			//使用UID登录
			$where['un'] = "uid='$username'";
		} elseif (isemail($username)) {
			//使用注册邮箱登录
			$where['un'] = "email='$username'";
		}
		$wheresql = implode(' AND ', $where);
		$sqlx = $sql.$wheresql;
		$result = DB::fetch_first($sqlx);
		if (!$result) {
			//使用用户名登录
			$where['un'] = "username='$username'";
			$wheresql = implode(' AND ', $where);
			$sqlx = $sql.$wheresql;
			$result = DB::fetch_first($sqlx);
		}
	} else {
		if ($isuid == 1) {
			//使用UID登录
			$where['un'] = "uid='$username'";
		} elseif ($isuid == 2) {
			//使用邮箱登录
			$where['un'] = "email='$username'";
		} else {
			//使用用户名登录
			$where['un'] = "username='$username'";
		}
		$wheresql = implode(' AND ', $where);
		$sql .= $wheresql;
		$query = DB::Query($sql);
		$r = DB::fetch($query);
		$result = DB::fetch_first($sql);
	}
	if (!$result) {
		$result['status'] = 0;
		return $result;
	}
	$ar = array('uid', 'username', 'password');
	foreach ($result as $k => $v) {
		if (in_array($k, $ar))
			$return[$k] = $v;
	}
	$return['member'] = $result;
	$return['status'] = 1;
	return $return;
}

/**
 * 设置用户登录状态
 * @global array $_G 系统全局变量
 * @param array $member 用户信息
 * @param int $cookietime 登录状态保留时间
 */
function setloginstatus($member, $cookietime) {
	global $_G;
	$_G['uid'] = $member['uid'];
	$_G['username'] = $member['username'];
	$_G['adminid'] = $member['adminid'];
	$_G['groupid'] = $member['groupid'];
	$_G['formhash'] = formhash();
	$_G['member'] = $member;
	$_G['core']->session->isnew = 1;
	dsetcookie('auth', authcode("{$member['password']}\t{$member['uid']}", 'ENCODE'), $cookietime, 1, true);
}

/**
 * 登录失败次数检测
 * @global array $_G 系统全局变量
 * @return int 还可以尝试登录次数
 */
function logincheck() {
	global $_G;
	$return = 0;
	$login = DB::fetch_first("SELECT count, lastupdate FROM #__common_failedlogin WHERE ip='$_G[clientip]'");
	$return = (!$login || (TIMESTAMP - $login['lastupdate'] > 900)) ? 4 : max(0, 5 - $login['count']);

	if (!$login) {
		DB::query("REPLACE INTO #__common_failedlogin (ip, count, lastupdate) VALUES ('$_G[clientip]', '1', '$_G[timestamp]')");
	} elseif (TIMESTAMP - $login['lastupdate'] > 900) {
		DB::query("REPLACE INTO #__common_failedlogin (ip, count, lastupdate) VALUES ('$_G[clientip]', '1', '$_G[timestamp]')");
		DB::query("DELETE FROM #__common_failedlogin WHERE lastupdate<$_G[timestamp]-901", 'UNBUFFERED');
	}
	return $return;
}

/**
 * 记录登录失败的记录
 * @global array $_G 系统全局变量
 */
function loginfailed() {
	global $_G;
	DB::query("UPDATE #__common_failedlogin SET count=count+1, lastupdate='$_G[timestamp]' WHERE ip='$_G[clientip]'");
}

/**
 * 替换提示信息中变量设置
 * @global array $_G 系统全局变量
 * @param string $string 信息内容
 * @param array $replaces 要替换的信息
 * @return string 已经替换掉的信息
 */
function replacesitevar($string, $replaces = array()) {
	global $_G;
	$sitevars = array(
		'{sitename}' => $_G['setting']['sitename'],
		'{time}' => dgmdate(TIMESTAMP, 'Y-n-j H:i'),
		'{adminemail}' => $_G['setting']['adminemail'],
		'{username}' => $_G['member']['username'],
		'{myname}' => $_G['member']['username']
	);
	$replaces = array_merge($sitevars, $replaces);
	return str_replace(array_keys($replaces), array_values($replaces), $string);
}

/**
 * 添加一个用户
 * @param string $username 用户名
 * @param string $password 密码
 * @param string $email 邮箱
 * @param int $questionid 提示问题
 * @param string $answer 答案
 * @return int 成功后返回用户ID
 */
function addmember($username, $password, $email, $questionid = 0, $answer = '') {
	if (($status = check_username($username)) < 0) {
		return status;
	}
	if (($status = check_email($email)) < 0) {
		return $status;
	}
	$data = array();
	$data['regip'] = $data['lastip'] = $_G['clientip'];
	$data['lastvisit'] = $data['lastactivity'] = TIMESTAMP;
	$data['lastpost'] = $data['lastsendmail'] = 0;
	$data['secques'] = '';
	if ($questionid > 0)
		$data['secques'] = quescrypt($questionid, $answer);
	$password = md5($password);
	$data['username'] = $username;
	$data['password'] = $password;
	$data['email'] = $email;
	$data['credits'] = intval($_G['setting']['initcredits']);
	DB::insert('common_member', $data);
	return DB::insert_id();
}

/**
 * 检测用户名是否重复
 * @param string $username 用户名
 * @return int 返回值：-3:用户名重复 1:不重复
 */
function check_username($username) {
	$data = DB::result_first("SELECT username FROM #__common_member WHERE username='$username'");
	if ($data)
		return -3;
	return 1;
}

/**
 * 检查邮箱是否可用
 * @param string $email 邮箱
 * @param string $username 用户名
 * @return int 返回值：-4:格式不对 -6:已经被使用 1:可用
 */
function check_email($email, $username = '') {
	//检查邮箱格式
	if (!strlen($email) > 6 && preg_match("/^[\w\-\.]+@[\w\-\.]+(\.\w+)+$/", $email)) {
		return -4;
	} elseif (check_emailexists($email, $username)) {	//检查邮箱是否已经被使用
		return -6;
	} else {
		return 1;
	}
}

/**
 * 检查邮箱是否已经存在
 * @param string $email 邮箱
 * @param string $username 用户名
 * @return boolean
 */
function check_emailexists($email, $username = '') {
	$sqladd = $username !== '' ? "AND username<>'$username'" : '';
	$email = DB::result_first("SELECT email FROM  #__common_member WHERE email='$email' $sqladd");
	return $email;
}

/**
 * 更新用户状态信息
 * @global array $_G 系统全局变量
 * @param int $uid 用户UID
 * @param array $counts  要改变的信息
 */
function member_status_update($uid, $counts) {
	global $_G;

	$setsqls = array();
	$newprompt = 0;
	foreach ($counts as $key => $value) {
		$setsqls[] = "{$key}={$key}+'{$value}'";
		$newprompt = $newprompt + $value;
	}
	if ($setsqls) {
		$setsqls[] = "newprompt=newprompt+'{$newprompt}'";
		$setsqls[] = "lastactivity='{$_G[timestamp]}'";
		DB::query("UPDATE #__common_member SET " . implode(',', $setsqls) . " WHERE uid='$uid'");
	}
}

/**
 * 读取指定用户的信息
 * @global array $_G 系统全局变量
 * @param int $uid 指定的用户ID
 * @return array 用户详细信息
 */
function getspace($uid) {
	global $_G;

	$var = "member_{$uid}";
	if (!isset($_G[$var])) {
		// 要查看的是否是自己的信息？
		if ($uid == $_G['uid'] && $_G['member']['uid']) {
			$_G[$var] = $_G['member'];
			$_G[$var]['self'] = 1;
		} else {
			$query = DB::query("SELECT * FROM #__common_member WHERE uid='$uid'");
			$_G[$var] = DB::fetch($query);
		}
	}
	return $_G[$var];
}

/**
 * 检查两次发布信息之间的等等时间
 * @global array $_G 系统全局变量
 * @return int 还需要等等的时间
 */
function interval_check() {
	global $_G;

	$waittime = 0;
	if (checkperm('disablepostctrl')) {
		return $waittime;
	}
	if ($_G['setting']['floodctrl']) {
		$waittime = $_G['setting']['floodctrl'] - ($_G['timestamp'] - $_G['member']['lastpost']);
	}
	return $waittime;
}

function checkusergroup($uid = 0) {
	include_once libfile('class/credit');
	$credit = & credit::instance();
	$credit->checkusergroup($uid);
}
